from django_redis import get_redis_connection
from rest_framework import serializers
from drf_haystack.serializers import HaystackSerializer
from goods.models import SKU
from goods.search_indexes import SKUIndex
from orders.models import OrderGoods, OrderInfo


class CategoriesListSerializer(serializers.ModelSerializer):
    """
    商品详情列表序列化器
    """
    class Meta:
        model = SKU
        fields = "__all__"

class SKUIndexSerializer(HaystackSerializer):
    """
    SKU索引序列化器
    """
    # 嵌套序列化返回
    object = CategoriesListSerializer() #SKU商品数据对象序列化返回
    class Meta:
        index_classes =[SKUIndex]
        fields= ("text","object")

class UserBrowseHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate_sku_id(self, value):
        """
        验证sku_id是否存在
        :param value:
        :return:
        """
        try:
          SKU.objects.get(id=value)
        except:
            raise serializers.ValidationError("商品不存在")
        return value

    def create(self, validated_data):
        user = self.context["request"].user
        # 建立redis连接
        coon = get_redis_connection("history")
        # 判断sku_id 是否保存过，如果保存过删除
        coon.lrem("history_%s" %user.id,0,validated_data["sku_id"] )
        # 写入sku_id
        coon.lpush("history_%s" %user.id,validated_data["sku_id"])
        # 指定范围 从0到4
        coon.ltrim("history_%s"%user.id,0,4)

        return validated_data


class SKUSerializer(serializers.ModelSerializer):

    count = serializers.IntegerField(read_only=True)

    class Meta:

        model = SKU
        fields = '__all__'


class OrdersSerializer(serializers.ModelSerializer):

    sku = SKUSerializer()
    class Meta:
        model = OrderGoods
        fields = '__all__'


class OrderShowSerializer(serializers.ModelSerializer):

    skus = OrdersSerializer(many=True)

    class Meta:

        model = OrderInfo
        fields = '__all__'